package com.parktech.sun.web.controller.management.news;

import com.parktech.sun.domain.model.Constants;
import com.parktech.sun.domain.model.news.News;
import com.parktech.sun.domain.model.news.NewsAttachment;
import com.parktech.sun.domain.repository.Page;
import com.parktech.sun.domain.service.news.NewsService;
import com.parktech.sun.utils.FileHelper;
import com.parktech.sun.utils.ImageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * User: Think
 * Date: 11-1-12
 * Time: 下午5:09
 */
@Controller
@RequestMapping("/management/news")
public class NewsController {
    
    private int pageSize = Constants.PAGINATION_PAGE_SIZE;

    private NewsService newsService;

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    @Autowired
    public NewsController(NewsService newsService) {
        this.newsService = newsService;
    }

    @RequestMapping(value = "/search", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView search(@ModelAttribute NewsSearchForm newsSearchForm) {

        Page page = new Page(pageSize, newsSearchForm.getPageNo());

        ModelAndView modelAndView = new ModelAndView("management/news/newsSearch");

        return modelAndView.addObject(
                newsService.search(
                        newsSearchForm.getTitle(), newsSearchForm.getCategory(), newsSearchForm.getPublishStatus(), page));
    }

    @RequestMapping(value = "/search", method = RequestMethod.DELETE)
    public String delete(@RequestParam("newsIds") Long[] newsIds) {
        newsService.deleteAll(newsIds);
        return "redirect:search";
    }

    @ModelAttribute("allCategories")
    public Map<Integer, String> populateAllCategories() {
        Map<Integer, String> allCategories = new TreeMap<Integer, String>();
        allCategories.put(1, "行业动态");
        allCategories.put(2, "协会动态");
        allCategories.put(3, "企业动态");
        allCategories.put(4, "政府动态");
        return allCategories;
    }

    @ModelAttribute("allPositions")
    public Map<Integer, String> populateAllPositions() {
        Map<Integer, String> allCategories = new TreeMap<Integer, String>();
        allCategories.put(1, "图片新闻");
        allCategories.put(2, "置顶新闻");
        allCategories.put(3, "普通显示");
        return allCategories;
    }

    @ModelAttribute("news")
    public News populateModel(HttpServletRequest request) {
        String strId = request.getParameter("id");

        if (strId == null || strId.equals("-1")) {
            return new News();
        }
        return newsService.getById(new Long(strId));
    }

    @ModelAttribute("allPublishStatus")
    public Map<Integer, String> populateAllPublishStatus() {
        Map<Integer, String> allPublishStatus = new HashMap<Integer, String>();
//        allPublishStatus.put(-1, "所有");
        allPublishStatus.put(0, "未发布");
        allPublishStatus.put(1, "已发布");
        return allPublishStatus;
    }

    @RequestMapping(value = "/{newsId}", method = RequestMethod.GET)
    public String edit(@PathVariable Long newsId, Model model) {
        News news = newsService.getById(newsId);
        model.addAttribute(news);
        return "management/news/newsForm";
    }

    @RequestMapping(method = RequestMethod.GET)
    public String create(Model model) {
        model.addAttribute(new News());
        return "management/news/newsForm";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String save(@ModelAttribute @Valid News news, BindingResult result,
                       @RequestParam("attachments") MultipartFile[] attachments,
                       @RequestParam("image") MultipartFile image,
                       @RequestParam("delAttachmentIds") Long[] delAttachmentIds,HttpServletRequest request)
            throws IOException {

        if (result.hasErrors()) {
            return "management/news/newsForm";
        }
        newsService.clearThenSaveOrUpdateBean(news);

        if (delAttachmentIds != null) {
            deleteAttachments(news, delAttachmentIds, request.getSession().getServletContext());
        }

        if (image != null && !image.isEmpty()) {
            processImage(news, image, request.getSession().getServletContext());
        }
        
        if (attachments.length > 0) {
            processAttachments(news, attachments, request.getSession().getServletContext());
        }
        newsService.saveOrUpdateBean(news);

        return "redirect:/management/news/search";
    }

    private void processImage(News news, MultipartFile image, ServletContext servletContext) throws IOException {

        String newsPath = servletContext.getRealPath("/upload/news/" + news.getId());
        File newsDir = new File(newsPath);
        if (!newsDir.exists()) newsDir.mkdirs();

        File imageFile = new File(newsDir, image.getOriginalFilename());
        if (imageFile.exists()) {
            imageFile.delete();
        }
//        ImageHelper.resizeFix(image.getInputStream(), imageFile, 150, 75);
        FileHelper.saveFile(image.getInputStream(), imageFile);
        news.setImageName(image.getOriginalFilename());
    }

    private void deleteAttachments(News news, Long[] delAttachmentIds, ServletContext servletContext) {
        List<NewsAttachment> attachmentList = news.getAttachmentList();
        if (attachmentList == null) {
            return ;
        }
        String newsPath = servletContext.getRealPath("/upload/news/" + news.getId());
        File newsDir = new File(newsPath);
        if (!newsDir.exists()) newsDir.mkdirs();

        for (Iterator<NewsAttachment> iterator = attachmentList.iterator(); iterator.hasNext(); ) {
            NewsAttachment attachment = iterator.next();
            for (Long delAttachmentId : delAttachmentIds) {
                if (attachment.getId().equals(delAttachmentId)) {
                    iterator.remove();
                    attachmentList.remove(attachment);
                    attachment.setNews(null);
                    File toDelFile = new File(newsDir, attachment.getName());
                    if (toDelFile.exists()) toDelFile.delete();
                }
            }
        }
    }

    private void processAttachments(News news, MultipartFile[] attachments, ServletContext servletContext) throws IOException {

        String newsPath = servletContext.getRealPath("/upload/news/" + news.getId());
        File newsDir = new File(newsPath);
        if (!newsDir.exists()) newsDir.mkdirs();

        List<NewsAttachment> attachmentList = news.getAttachmentList();
        if (attachmentList == null) {
            attachmentList = new ArrayList<NewsAttachment>();
            news.setAttachmentList(attachmentList);
        }
        for (MultipartFile attachment : attachments) {
            if (attachment == null || attachment.isEmpty()) {
                continue;
            }
            String originalFilename = attachment.getOriginalFilename();
            File target = new File(newsDir, attachment.getOriginalFilename());
            if (target.exists()) {
                target.delete();
            } else {
                attachmentList.add(new NewsAttachment(originalFilename, news));
            }

            FileHelper.saveFile(attachment.getInputStream(), target);
        }
    }
    
}
